<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="/plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">

    <link rel="stylesheet" href="/layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="/plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="/plugins/zTree/css/metroStyle/ext.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_3564966_a6tt4yhnzge.css" media="all">
    <style>
        .bg_no_data{
            opacity: 0.5;
            height: 100%;
            background: rgba(0, 0, 0, 0) url("/img/empty.png") no-repeat scroll center center;
            background-position-x: center;
            background-position-y: center;
            background-size: auto;
            display: block;
            background-position: 50% 10%;
            background: ;
            background-size: 20%;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div style="display: flex;">
        <div style="width: 300px; border-right: 2px solid #080720;">
            <div class="layui-card">

                <div class="layui-card-body">
                    <div class="layui-card-header action-edit layui-hide">
                        <span></span>
                        <div class="layui-btn-group layuiadmin-btn-group">
                            <a href="javascript:onAdd();" class="layui-btn layui-btn-normal layui-btn-xs action-edit">新增养殖场</a>
                        </div>
                    </div>
                    <div class="layui-card-body">
                        <div class="tree-div scroll" >
                            <ul id="treeDemo" class="ztree"></ul>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <div id="right-box" style="width: calc(100% - 300px);float: right; " >
            <blockquote class="layui-elem-quote" id="tip">请在左侧选择</blockquote>
            <div id="right-box-content" style="background: #0a1434;height: calc(100% - 50px);">
                <div class="no_data bg_no_data" >
                </div>

                <div class="box_farm" style="display: none;">
                    <form class="layui-form " lay-filter="form_farm" id="form_farm" style="padding: 20px 30px 0 0;">
                        <input class="layui-hide" type="text" name="id" lay-verify="">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">养殖场名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="farmname" lay-verify="required" lay-verType="tips" placeholder="请输入名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>


                        <div class="layui-form-item action-allocate layui-hide">
                            <label class="layui-form-label">人员分配</label>
                            <div class="layui-input-inline">
                                <div id="users" class="demo-transfer"></div>
                            </div>
                        </div>

                        <div class="layui-form-item action-allocate layui-hide" >
                            <label class="layui-form-label">绑定设备</label>
                            <div class="layui-input-inline">
                                <div id="devices" class="demo-transfer"></div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal action-edit layui-hide" lay-submit="" lay-filter="btn_save_farm" id="btn_save_farm"><i class="layui-icon layui-icon-release"></i> 保存</button>
                            </div>
                        </div>
                    </form>
                </div>





                <div class="box_house" style="display: none;">
                    <form class="layui-form " lay-filter="form_house" id="form_house" style="padding: 20px 30px 0 0;">
                        <input class="layui-hide" type="text" name="id" lay-verify="">
                        <input class="layui-hide" type="text" name="farmid" lay-verify="">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="housename" lay-verify="required" lay-verType="tips" placeholder="请输入名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>

                        <!--<div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">栏位行列</label>
                                <div class="layui-input-inline" style="width: 80px;margin-right:0px;">
                                    <input type="text" style="width: 80px;" name="room_row_num" lay-verify="number" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input">
                                </div>
                                <label class="layui-form-label" style="width: 10px;padding: 9px 10px;">x</label>
                                <div class="layui-input-inline" style="width: 80px;">
                                    <input type="text" style="width: 80px;" name="room_col_num" lay-verify="number" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal action-edit layui-hide" lay-submit="" lay-filter="btn_open_rooms" id="btn_open_rooms"><i class="layui-icon layui-icon-table"></i> 栏位设置</button>
                            </div>
                        </div>-->


                        <div class="layui-form-item action-allocate layui-hide" >
                            <label class="layui-form-label">绑定设备</label>
                            <div class="layui-input-inline">
                                <div id="devices1" class="demo-transfer"></div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal action-edit layui-hide" lay-submit="" lay-filter="btn_save_house" id="btn_save_house"><i class="layui-icon layui-icon-release"></i> 保存</button>
                            </div>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>
</div>

<script src="/plugins/layui/layui.js"></script>
<script src="/plugins/layui/xm-select-v1.2.4.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="/plugins/zTree/js/jquery.ztree.core.min.js"></script>
<script src="/plugins/zTree/js/jquery.ztree.excheck.js"></script>
<script src="/plugins/zTree/js/jquery.ztree.exedit.js"></script>
<script src="/plugins/jtopo/jtopo_fixbug.js"></script>
<script src="/plugins/jquery.slimscroll.min.js"></script>
<script>

    var lay_index=null;
    var zTree=null;
    var table=null;
    var laydate=null;
    var form=null;
    var element=null;
    //var transfer=null;
    var actions=null;
    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    var users = [];
    var devices = [];
    var selectedTreeNode=null;
    var afterAddFarm = false;
    var afterAddHouse = false;
    var cur_farm = null;
    var cur_house = null;
    var new_house_id = null;
    var selectUser = null;
    var selectDevice = null;
    var selectDevice1 = null;

    var canvas=null;
    var stage=null;
    var scene=null;
    var currentNode=null;
    var menu=null;

    token = 'Bearer ' + token;
    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table','form','element','transfer'], function(){
        $ = layui.$;
        form = layui.form;
        element = layui.element;
        //transfer = layui.transfer;

        $.ajax({
            type: 'GET',
            url: '/Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url: "/Api/User/List",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res);
                if(res.code>=0){
                    users = res.data;
                    //加载tree
                    loadTree();
                }else{
                    layer.alert(res.msg);

                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url: "/Api/User/Devices",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res);
                if(res.code>=0){
                    //devices = res.data;
                    devices=[];
                    for(var i=0;i<res.data.length;i++){
                        devices.push({
                            device_addr:res.data[i].device_addr+"/"+res.data[i].device_type,
                            name:res.data[i].device_addr+" "+res.data[i].remark +" "+res.data[i].device_type
                        });
                    }
                }else{
                    layer.alert(res.msg);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        form.on('submit(btn_save_farm)', function(data){
            /*var trans = transfer.getData('trans-users');
            var array=[];
            for(var i=0;i<trans.length;i++){
                array.push(trans[i].value);
            }
            //console.info(array);
            if(array.length>0){
                data.field.users = (array.join(","));
            }*/
            data.field.users = selectUser.getValue('valueStr');
            data.field.devices = selectDevice.getValue('valueStr');


            console.info(data.field);
            var request = "";
            if(data.field.id.length>0){
                request = "PUT";
            }else{
                request = "POST";
            }
            layer.load(1);
            $.ajax({
                type: request,
                url: '../Api/Farm',
                data: data.field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        if(data.field.id.length>0){
                            //修改
                        }else{
                            selectedTreeNode = null;
                            afterAddFarm = true;
                        }

                        loadTree();
                    }else{
                        layer.alert(res.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        });

        form.on('submit(btn_save_house)', function(data){
            data.field.devices = selectDevice1.getValue('valueStr');
            console.info(data.field);
            var request = "";
            if(data.field.id.length>0){
                request = "PUT";
            }else{
                request = "POST";
            }
            layer.load(1);
            $.ajax({
                type: request,
                url: '../Api/House',
                data: data.field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        if(data.field.id.length>0){
                            //修改
                        }else{
                            selectedTreeNode = null;
                            afterAddHouse = true;
                            new_house_id = res.data;
                        }

                        loadTree();
                    }else{
                        layer.alert(res.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        });

        form.on('submit(btn_open_rooms)', function(data){
            console.info(data.field);
            onSetRooms(data.field.room_row_num,data.field.room_col_num);
        });

        form.on('submit(btn_bind)', function(data){
            console.info(data.field);
            //return ;
            var request = "";
            if(data.field.id.length>0){
                request = "PUT";
            }else{
                request = "POST";
            }
            layer.load(1);
            $.ajax({
                type: request,
                url: '../Api/Room',
                data: data.field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        //
                        layer.close(lay_index);

                        //加载栏位
                        layer.load(1);
                        $.ajax({
                            type: 'GET',
                            url: '../Api/Room',
                            data: {houseid:selectedTreeNode.id},
                            beforeSend: function(request) {
                                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                            },
                            dataType: "json",
                            success: function (res) {
                                if(res.code>=0){
                                    console.info(res.data);
                                    renderMap(res.data,cur_house.room_row_num,cur_house.room_col_num);
                                }else{
                                    layer.alert(res.msg);
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg('加载信息失败');
                            },
                            complete: function(XMLHttpRequest, textStatus) {
                                layer.closeAll('loading');
                            },

                        });
                    }else{
                        layer.alert(res.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        });

        resizeElement();

        initCanvas();
    });

    var tree_setting = {
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
            //addHoverDom: addHoverDom,
            //removeHoverDom: removeHoverDom,
            addDiyDom:addHoverDom
        },
        callback: {
            onClick: treeOnClick,
            //onRightClick: OnRightClick,
            //拖拽时鼠标放开事件
            //onDrop: treeOnDrop,
            //beforeDrag: treeBeforeDrag,
            //beforeExpand: zTreeBeforeExpand
            //onExpand:treeOnExpand,
            //onCollapse:treeOnCollapse,
        },
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false,
            drag:{
                autoExpandTrigger: false,
                isCopy: false,
                prev: false,
                next: false,
                inner: false
            }
        },
    };
    function addHoverDom(treeId, treeNode){
        selectedTreeNode = treeNode;
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        var addStr = "<span class='button add' nodeid='"+treeNode.tId+"' id='addBtn_" + treeNode.tId
            + "' title='新增'' onfocus='this.blur();'></span>";

        var removeStr = "<span class='button remove' nodeid='"+treeNode.tId+"' id='removeBtn_" + treeNode.tId
            + "' title='删除' onfocus='this.blur();'></span>";

        if(treeNode.type=="farm"||treeNode.type=="house")
        {
            sObj.after(removeStr);
        }

        var btn = $("#removeBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(event){
            var tid = $(this).attr("nodeid");
            var node = zTree.getNodeByTId(tid);
            onRemove();
        });
        if(treeNode.type=="farm")
        {
            sObj.after(addStr);
        }

        btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function (event) {
            var tid = $(this).attr("nodeid");
            var node = zTree.getNodeByTId(tid);
            onAdd();
            return false;
        });
    }
    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
        $("#editBtn_"+treeNode.tId).unbind().remove();
        $("#removeBtn_"+treeNode.tId).unbind().remove();
    };
    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }

    function loadTree() {
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Farm/Topo',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    var nodes=setDataIcon(res.data);
                    //console.info(nodes);
                    zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);

                    //
                    if(selectedTreeNode){
                        console.info(selectedTreeNode);
                        if(selectedTreeNode.type=="farm"){
                            var nodes = zTree.getNodesByParam("farmid", selectedTreeNode.id, null);
                            if(nodes.length>0){
                                const node = nodes[0];
                                console.info(node);
                                zTree.selectNode(node);
                                zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                            }
                        }
                        else if(selectedTreeNode.type=="house"){
                            var nodes = zTree.getNodesByParam("houseid", selectedTreeNode.id, null);
                            if(nodes.length>0){
                                const node = nodes[0];
                                console.info(node);
                                zTree.selectNode(node);
                                zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                            }
                        }

                    }else{

                        if(afterAddFarm){
                            afterAddFarm = false;
                            var nodes = zTree.getNodesByParam("type", "farm", null);
                            if(nodes.length>0){
                                const node = nodes[nodes.length-1];
                                console.info(node);
                                zTree.selectNode(node);
                                zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                            }
                        }
                        else if(afterAddHouse){
                            afterAddHouse = false;
                            var nodes = zTree.getNodesByParam("houseid", new_house_id, null);
                            new_house_id = null;
                            if(nodes.length>0){
                                const node = nodes[nodes.length-1];
                                console.info(node);
                                zTree.selectNode(node);
                                zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                            }
                        }
                        else{
                            var nodes = zTree.getNodesByParam("type", "farm", null);
                            if(nodes.length>0){
                                const node = nodes[0];
                                console.info(node);
                                zTree.selectNode(node);
                                zTree.setting.callback.onClick(null,null,node);//手动触发onClick事件
                            }
                        }

                    }
                }else{
                    layer.alert(res.msg);
                }
                //zTree.expandAll(true);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });
    }


    function onAdd() {
        if(!selectedTreeNode){
            $("#right-box-content").children("div").hide();
            onAddFarm();
        }else if(selectedTreeNode.type=="root"){
            $("#right-box-content").children("div").hide();
            onAddFarm();
        }
        else if(selectedTreeNode.type=="farm"){
            $("#right-box-content").children("div").hide();
            onAddHouse();
        }
    }
    function onRemove() {
        if(selectedTreeNode.type=="farm"){
            onRemoveFarm();
        }else if(selectedTreeNode.type=="house"){
            onRemoveHouse();
        }
        return false;
    }

    function treeOnClick(event, treeId, treeNode) {
        selectedTreeNode=treeNode;
        if(selectedTreeNode.type=="root"){
            $("#right-box-content").children("div").hide();
            $(".no_data").show();
            $("#tip").html('');
        }else if(selectedTreeNode.type=="farm"){
            $("#right-box-content").children("div").hide();
            onEditFarm();
        }else if(selectedTreeNode.type=="house"){
            $("#right-box-content").children("div").hide();
            onEditHouse();
        }
    }
    function onAddFarm(){
        $(".box_farm").show();
        $("#tip").html("新增养殖场");

        /*transfer.render({
            elem: '#users'  //绑定元素
            ,title:['全部', '已经选取']
            ,data: users
            ,height:250
            ,parseData: function(res){
                return {
                    "value": res.userid //数据值
                    ,"title": res.name //数据标题
                    ,"disabled": false  //是否禁用
                    ,"checked": false //是否选中
                }
            }
            ,value: null
            ,id: 'trans' //定义索引
        });

        transfer.render({
            elem: '#devices'  //绑定元素
            ,title:['全部', '已经选取']
            ,data: devices
            ,height:250
            ,parseData: function(res){
                return {
                    "value": res.daddr //数据值
                    ,"title": res.name //数据标题
                    ,"disabled": false  //是否禁用
                    ,"checked": false //是否选中
                }
            }
            ,value: null
            ,id: 'trans' //定义索引
        });*/

        selectUser = xmSelect.render({
            el: '#users',
            tips: '选择操作',
            filterable: true,
            direction: 'auto',
            theme: {
                color: '#4958b9'
            },
            prop: {
                name: 'name',
                value: 'userid',
            },
            data: users
        });
        selectUser.setValue([]);

        selectDevice = xmSelect.render({
            el: '#devices',
            tips: '选择操作',
            filterable: true,
            direction: 'auto',
            theme: {
                color: '#4958b9'
            },
            prop: {
                name: 'name',
                value: 'device_addr',
            },
            data: devices
        });
        selectDevice.setValue([]);

        form.val('form_farm',{id:'',farmname:''});
    }
    function onEditFarm() {
        $(".box_farm").show();
        $("#tip").html(selectedTreeNode.name);



        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Farm',
            data: {id:selectedTreeNode.id},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    if(res.count>0){
                        cur_farm  = res.data[0];
                        //console.info(item);
                        form.val('form_farm',cur_farm);

                        /*transfer.render({
                            elem: '#users'  //绑定元素
                            ,title:['全部', '已经选取']
                            ,data: users
                            ,height:250
                            ,parseData: function(res){
                                return {
                                    "value": res.userid //数据值
                                    ,"title": res.name //数据标题
                                    ,"disabled": false  //是否禁用
                                    ,"checked": false //是否选中
                                }
                            }
                            ,value: cur_farm.users==null?null:cur_farm.users.split(',')
                            ,id: 'trans-users' //定义索引
                        });


                        transfer.render({
                            elem: '#devices'  //绑定元素
                            ,title:['全部', '已经选取']
                            ,data: devices
                            ,height:250
                            ,parseData: function(res){
                                return {
                                    "value": res.daddr //数据值
                                    ,"title": res.name //数据标题
                                    ,"disabled": false  //是否禁用
                                    ,"checked": false //是否选中
                                }
                            }
                            ,value: null
                            ,id: 'trans-devices' //定义索引
                        });*/

                        selectUser = xmSelect.render({
                            el: '#users',
                            tips: '选择操作',
                            filterable: true,
                            direction: 'auto',
                            theme: {
                                color: '#4958b9'
                            },
                            prop: {
                                name: 'name',
                                value: 'userid',
                            },
                            data: users
                        });
                        var val = (cur_farm.users==null?null:cur_farm.users.split(','));
                        selectUser.setValue(val);

                        selectDevice = xmSelect.render({
                            el: '#devices',
                            tips: '选择操作',
                            filterable: true,
                            direction: 'auto',
                            theme: {
                                color: '#4958b9'
                            },
                            prop: {
                                name: 'name',
                                value: 'device_addr',
                            },
                            data: devices
                        });

                        var arr =[];
                        if(cur_farm.devices){
                            for(var i=0;i<cur_farm.devices.length;i++){
                                arr.push(cur_farm.devices[i]["device_addr"]+"/"+cur_farm.devices[i]["device_type"]);
                            }

                        }
                        selectDevice.setValue(arr);
                    }

                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });
    }
    function onRemoveFarm(){
        layer.confirm('确定删除'+selectedTreeNode.name+'?', function(index){
            layer.close(index); //再执行关闭
            layer.load(1);
            $.ajax({
                type: 'DELETE',
                url: '../Api/Farm',
                data: {id:selectedTreeNode.id},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        selectedTreeNode = null;
                        loadTree();
                    }else{
                        layer.alert(res.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        })
    }

    function onAddHouse(){
        $("#btn_open_rooms").removeClass("layui-btn-normal").addClass("layui-btn-disabled");
        $('#btn_open_rooms').attr("disabled",true)//将input元素设置为disabled
        $(".box_house").show();
        $("#tip").html('新增栏舍');
        /*transfer.render({
            elem: '#devices1'  //绑定元素
            ,title:['全部', '已经选取']
            ,data: devices
            ,height:250
            ,parseData: function(res){
                return {
                    "value": res.daddr //数据值
                    ,"title": res.name //数据标题
                    ,"disabled": false  //是否禁用
                    ,"checked": false //是否选中
                }
            }
            ,value: null
            ,id: 'trans-devices1' //定义索引
        });*/
        selectDevice1 = xmSelect.render({
            el: '#devices1',
            tips: '选择操作',
            filterable: true,
            direction: 'auto',
            theme: {
                color: '#4958b9'
            },
            prop: {
                name: 'name',
                value: 'device_addr',
            },
            data: devices
        });
        selectDevice1.setValue([]);

        form.val('form_house',{id:'',farmid:selectedTreeNode.id,housename:'',room_row_num:0,room_col_num:0});
    }
    function onEditHouse() {
        $("#btn_open_rooms").removeClass("layui-btn-disabled").addClass("layui-btn-normal");
        $('#btn_open_rooms').attr("disabled",false)//将input元素设置为disabled
        $(".box_house").show();
        $("#tip").html(selectedTreeNode.name);
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/House',
            data: {id:selectedTreeNode.id},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    if(res.count>0){
                        cur_house  = res.data[0];
                        //console.info(item);
                        form.val('form_house',cur_house);

                        /*transfer.render({
                            elem: '#devices1'  //绑定元素
                            ,title:['全部', '已经选取']
                            ,data: devices
                            ,height:250
                            ,parseData: function(res){
                                return {
                                    "value": res.daddr //数据值
                                    ,"title": res.name //数据标题
                                    ,"disabled": false  //是否禁用
                                    ,"checked": false //是否选中
                                }
                            }
                            ,value: null
                            ,id: 'trans-devices1' //定义索引
                        });*/

                        selectDevice1 = xmSelect.render({
                            el: '#devices1',
                            tips: '选择操作',
                            filterable: true,
                            direction: 'auto',
                            theme: {
                                color: '#4958b9'
                            },
                            prop: {
                                name: 'name',
                                value: 'device_addr',
                            },
                            data: devices
                        });

                        var arr =[];
                        if(cur_house.devices){
                            for(var i=0;i<cur_house.devices.length;i++){
                                arr.push(cur_house.devices[i]["device_addr"]+"/"+cur_house.devices[i]["device_type"]);
                            }
                        }else{
                        }
                        selectDevice1.setValue(arr);
                    }

                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });

    }
    function onRemoveHouse(){
        layer.confirm('确定删除'+selectedTreeNode.name+'?', function(index){
            layer.close(index); //再执行关闭
            layer.load(1);
            $.ajax({
                type: 'DELETE',
                url: '../Api/House',
                data: {id:selectedTreeNode.id},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (res) {
                    if(res.code>=0){
                        selectedTreeNode = null;
                        loadTree();
                    }else{
                        layer.alert(res.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('加载信息失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },

            });
        })
    }

    function onSetRooms(room_row_num,room_col_num){
        if(room_row_num==0 || room_col_num==0){
            layer.alert("行或列不能是0");
            return ;
        }
        layer.open({
            area:['900px','600px'],
            type: 1,
            shade: 0.6,
            shadeClose:true,
            title: '栏位设置', //不显示标题
            content: $('#form_rooms'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['完成']
            ,yes: function(index, layero){
                lay_index=index;
                layer.close(lay_index);
            }
        });

        //加载栏位
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Room',
            data: {houseid:selectedTreeNode.id},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                if(res.code>=0){
                    console.info(res.data);
                    renderMap(res.data,room_row_num,room_col_num);
                }else{
                    layer.alert(res.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },

        });


    }

    function onRoomBinding(){
        $("#menu").hide();
        console.info(currentNode);
        layer.open({
            //area: 'auto',
            area:['300px','200px'],
            type: 1,
            shade: 0.6,
            shadeClose:true,
            title: currentNode.name, //不显示标题
            content: $('#form_bind'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_bind");
                submit.click();
            }
        });

        form.val('form_bind',{houseid:selectedTreeNode.id,id:currentNode.room_id,code:currentNode.code,row:currentNode.room_row,col:currentNode.room_col});
    }


    function initCanvas(){
        canvas = document.getElementById('canvas');
        stage = new JTopo.Stage(canvas);
        stage.mode = "select";
        stage.wheelZoom = 0.85;
        scene = new JTopo.Scene(stage);
        scene.click(function(event){
            //console.log("scene单击");
            $("#menu").hide();
        });
    }

    //渲染节点
    var trans_bg="10,20,52";
    var offline_color="100,100,100";
    var disable_color="0,0,0";
    var orange_color="255,222,173";
    var blue_color="0,255,255";
    var nanmu_orange_bg="242,145,20";
    var nanmu_blue_bg="0,161,186";
    var offline_bg="100,100,100";
    var white_color = "255,255,255";
    var select_color = "204,204,0";

    var nanmu_orange = "#F29114";
    var nanmu_blue = "#00A1BA";
    var nanmu_green = "#33ff3d";

    var ok_color = "0,255,0";
    var err_color = "255,0,0";
    function renderMap(room_data,room_row_num,room_col_num){
        var n = scene.getDisplayedNodes();
        //console.info(n);
        for(var i=0;i<n.length;i++){
            scene.remove(n[i]);
        }
        scene.clear();//删除所有节点
        if(!room_row_num||!room_col_num){
            return;
        }

        var row = room_row_num;
        var col = room_col_num;

        var x=50;
        var y=50;
        var offsetX=90;
        var offsetY=60;
        for(var i=0;i<row;i++){
            for(var j=0;j<col;j++){

                //查找是否绑定
                var code = '';
                var room_id = '';
                if(room_data.length>0){
                    var matchs=$.grep(room_data,function(item){
                        return item.row==i && item.col==j;
                    });
                    if(matchs.length>0){
                        code = matchs[0].code;
                        room_id = matchs[0].id;
                    }
                }

                var node = new JTopo.Node();
                node.type = "room";
                node.status = ""; //下发状态
                node.room_row = i;
                node.room_col = j;
                node.code = code;//绑定的控制器
                node.room_id = room_id;
                node.text = '行:'+(i+1)+' 列:'+(j+1); // 文字
                node.name = '行:'+(i+1)+' 列:'+(j+1); // 文字
                node.select =false;
                node.fontColor=white_color;
                node.textPosition = "Middle_Center";
                node.textOffsetY = -20;
                node.font = '10px 微软雅黑';
                node.showSelected = false;//不显示默认的选中
                node.dragable =false;
                node.setLocation(x+(offsetX*j), y+(offsetY*i)); // 位置
                node.setSize(80, 50);  // 尺寸
                node.borderRadius = 0; // 圆角
                node.borderWidth = 1; // 边框的宽度
                node.borderColor = (code.length>0?nanmu_blue_bg:white_color) ; //边框颜色
                node.alpha = 1; //透明度
                node.fillColor = (code.length>0?nanmu_blue_bg:trans_bg);
                scene.add(node);
                bindNodeEvent(node);

                //编码
                if(code.length>0){
                    var textNode = new JTopo.TextNode(code);
                    textNode.room_row = i;
                    textNode.room_col = j;
                    textNode.code = code;//绑定的控制器
                    textNode.room_id = room_id;
                    textNode.type="code";
                    textNode.font = '14px 微软雅黑';
                    textNode.setLocation(x+(offsetX*j)+25, y+(offsetY*i)+15); // 位置
                    //textNode.setSize(100, 15);
                    textNode.fontColor=white_color; //透明
                    textNode.showSelected = false;
                    textNode.dragable =false;
                    scene.add(textNode);
                    //all_nodes.push(textNode);
                    bindNodeEvent(textNode);
                }

            }
        }
    }
    //绑定节点事件
    function bindNodeEvent(node){

        node.mouseup(function(event){
            currentNode = this;
            if(event.button == 0){
                // 点击
                console.info(currentNode);
            }else if(event.button == 2){
                // 右键
                console.info(currentNode);
                // 当前位置弹出菜单（div）
                menu=$("#menu");
                menu.css({
                    top: event.pageY,
                    left: event.pageX
                }).show();
            }
        });
        node.click(function(event){
            currentNode = this;
        });
    }
    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='root'){
                node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                node.isParent=true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                node.isParent=true;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                node.isParent=false;
                if(node.device_online)
                {
                    node['font']={'color':'#3c7cff'};
                }else{
                    node['font']={'color':'#A3A8B6'};
                }
                //node['font']={'color':'#4958b9','font-weight':"bold"};
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }
    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        $('.tree-div').height($(window).height()-30-70);
        /*var h = $(window).height();

        $(".tree-div").slimScroll({
            height: h-25,
            size: '4px', //组件宽度
            color: '#eee', //滚动条颜色
            position: 'right', //组件位置：left/right
            distance: '0px', //组件与侧边之间的距离
            start: 'top', //默认滚动位置：top/bottom
            opacity: .4, //滚动条透明度
            alwaysVisible: true, //是否 始终显示组件
            disableFadeOut: false, //是否 鼠标经过可滚动区域时显示组件，离开时隐藏组件
            railVisible: true, //是否 显示轨道
            railColor: '#333', //轨道颜色
            railOpacity: .2, //轨道透明度
            railDraggable: true, //是否 滚动条可拖动
            railClass: 'slimScrollRail', //轨道div类名
            barClass: 'slimScrollBar', //滚动条div类名
            wrapperClass: 'slimScrollDiv', //外包div类名
            allowPageScroll: true, //是否 使用滚轮到达顶端/底端时，滚动窗口
            wheelStep: 10, //滚轮滚动量
            touchScrollStep: 200, //滚动量当用户使用手势
            borderRadius: '7px', //滚动条圆角
            railBorderRadius: '7px' //轨道圆角
        });*/
    }
</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>

<form class="layui-form" lay-filter="form_rooms" id="form_rooms" style="display:none;">
    <!--<div class="layui-form-item" style="margin-top: 10px;">

    </div>-->

    <!--<div class="layui-btn-group" style="float: right; margin-right: 10px;">
        <button type="button" onclick="onSelectAll();" style="width: 76px;" class="layui-btn layui-btn-sm layui-btn-primary layui-border-blue  onSelectAll"> <span class="">全选</span>  </button>
        <button type="button" onclick="onUnSelectAll();" style="width: 76px;" class="layui-btn layui-btn-sm layui-btn-primary layui-border-blue  onUnSelectAll"> 全不选  </button>
        <button type="button" onclick="onUnSelectReverse();" style="width: 76px;" class="layui-btn layui-btn-sm layui-btn-primary layui-border-blue  onUnSelectReverse"> 反选  </button>
    </div>-->
    <div id="canvas_contain" style="width: 900px;height: 450px; ">
        <canvas style="width: 900px;height: 450px;border-top: 1px dashed #EEEEEE;border-bottom: 1px dashed #EEEEEE;" width="900" height="450" ondragstart="return false;"  class=" center-block" id="canvas" >
        </canvas>
    </div>

    <div class="layui-form-item" style="margin: 10px;">
        <i class="iconfont icon-tishi layui-text-orange" style="font-size: 16px;"> </i><span>在任意栏位鼠标右键操作菜单,虚线内空白区域可通过鼠标拖动缩放。</span>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_apply" id="btn_apply" value="确认">
    </div>
</form>

<style>
    .contextmenu {
        border-bottom: 0;
        background: #4958b9;
        position: absolute;
        list-style: none;
        margin: 0;
        padding: 0;
        display: none;
        z-index: 99999999;
    }

    .contextmenu li{
        width: 160px;
    }

    .contextmenu li a {
        display: block;
        padding: 5px 20px;
        border: 1px solid #ffffffaa;
        cursor: pointer;
        color: #ccc;
    }
    .contextmenu li a:hover {
        background: #4958b9;
        color: #fff;
    }
</style>

<ul id="menu" class="contextmenu" style="display:none;">
    <li class=""  ><a onclick="onRoomBinding()"><i class="iconfont icon-tishi layui-text-orange"></i> 修改栏位</a></li>
</ul>

<form class="layui-form" lay-filter="form_bind" id="form_bind" style="display:none;padding: 20px 30px 0 0;">
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">houseid</label>
        <div class="layui-input-block">
            <input type="text" name="houseid" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
            <input type="text" name="id" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">row</label>
        <div class="layui-input-block">
            <input type="text" name="row" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">col</label>
        <div class="layui-input-block">
            <input type="text" name="col" lay-verify="" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">饲喂器编号</label>
        <div class="layui-input-block">
            <input type="text" name="code" lay-verify="required" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input" style="width: 100%">
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_bind" id="btn_bind" value="确认">
    </div>
</form>

</html>